import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/baseblocs/bloc_provider.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/person/entity/fuli_sum_entity.dart';
import 'package:shopping_group/modle/person/entity/rb_acctchg_entity.dart';
import 'package:shopping_group/utils/network_utils.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';

class MyFuLijuanBloc implements BlocBase {
  List<RbAcctChgEntity> _listEntity = [];
  String _hasMore = '0';
  int _pageNo = 1;
  ScrollController _scrollController;

  StreamController<Object> _initController = StreamController<Object>();
  StreamSink get initDate => _initController.sink;

  StreamController<Object> _allController = StreamController<Object>();
  StreamSink get _addDate => _allController.sink;
  Stream<Object> get sendData => _allController.stream;

  StreamController<Object> _initSumController = StreamController<Object>();
  StreamSink get initSumDate => _initSumController.sink;

  StreamController<Object> _allSumController = StreamController<Object>();
  StreamSink get _addSumDate => _allSumController.sink;
  Stream<Object> get sendSumData => _allSumController.stream;

  //处理more响应
  StreamController<ScrollController> _actionMoreController =
      StreamController<ScrollController>();
  StreamSink get moreDate => _actionMoreController.sink;

  //处理上拉刷新
  StreamController<ScrollController> _actionRefreshController =
      StreamController<ScrollController>();
  StreamSink get refreshDate => _actionRefreshController.sink;

  MyFuLijuanBloc() {
    _initController.stream.listen(initData);
    _actionMoreController.stream.listen(loadMoreData);
    _actionRefreshController.stream.listen(refreshData);
    _initSumController.stream.listen(sumData);
  }
  void sumData(data) {
    _sumTask();
  }

  void initData(data) {
    _listEntity?.clear();
    _pageNo = 1;
    Future.wait([
      _initTask(_pageNo.toString()),
    ]);
  }

  void refreshData(data) {
    _pageNo = 1;
    _listEntity?.clear();
    _initTask(_pageNo.toString());
  }

  void loadMoreData(controller) {
    if (controller is ScrollController) {
      _scrollController = controller;
      var maxScroll = _scrollController.position.maxScrollExtent;
      var pixel = _scrollController.position.pixels;
      var count = _listEntity.length;
      var length = int.parse(_hasMore);
      if (maxScroll == pixel && count > 0 && count < length) {
        _pageNo++;
        _initTask(_pageNo);
      }
    }
  }

  Future _sumTask() async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    Map<String, dynamic> data = {};
    if (ObjectUtil.isEmptyString(BaseConstant.userId)) {
      return;
    }
    data['val'] = BaseConstant.userId;
    //BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.FLJ_SUM_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            FuliSumEntity entity = FuliSumEntity.fromJson(result);
            _addSumDate.add(entity);
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  Future _initTask(pageNo) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    Map<String, dynamic> data = {};
    data['val'] = BaseConstant.userId;
    data['pageIndex'] = pageNo;
    data['pageSize'] = BaseConstant.PAGE_MAX_SIZE;
    //BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.FLJ_LIST_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            if (null != result) {
              List list = List.from(result['data']);
              if (ObjectUtil.isEmptyList(list)) {
                list = [];
              }
              for (var item in list) {
                _listEntity.add(RbAcctChgEntity.fromJson(item));
              }
              _hasMore = result['total'].toString();
            }
            _addDate.add(_listEntity);
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  @override
  void dispose() {
    _initController?.close();
    _allController?.close();
    _actionMoreController?.close();
    _actionRefreshController?.close();
    _initSumController?.close();
    _allSumController?.close();
  }
}
